import { type AIAgent } from './interface'
import { useAuthStore } from '../stores/auth' // 导入 useAuthStore
import { type Router } from 'vue-router'

export function isImage(url: string) {
  const expr = /\.(jpg|jpeg|png|gif|bmp|svg)$/i
  return expr.test(url)
}

export function processContent(content: string) {
  // 如果是图片链接地址，则直接替换成图片标签
  const linkRegex = /(https?:\/\/\S+)/g
  const links = content.match(linkRegex)
  if (links) {
    for (const link of links) {
      if (isImage(link)) {
        const index = content.indexOf(link)
        if (content.substring(index - 1, 2) !== ']') {
          content = content.replace(link, '\n![](' + link + ')\n')
        }
      }
    }
  }

  const lines = content.split('\n')
  if (lines.length <= 1) {
    return content
  }
  const texts = []
  // 定义匹配数学公式的正则表达式
  const formulaRegex = /^\s*[a-z|A-Z]+[^=]+\s*=\s*[^=]+$/
  let hasCode = false
  for (let i = 0; i < lines.length; i++) {
    // 处理引用块换行
    if (lines[i].startsWith('>')) {
      texts.push(lines[i])
      texts.push('\n')
      continue
    }
    // 如果包含代码块则跳过公式检测
    if (lines[i].indexOf('```') !== -1) {
      texts.push(lines[i])
      hasCode = true
      continue
    }
    // 识别并处理数学公式，需要排除那些已经被识别出来的公式
    if (i > 0 && formulaRegex.test(lines[i]) && lines[i - 1].indexOf('$$') === -1 && !hasCode) {
      texts.push('$$')
      texts.push(lines[i])
      texts.push('$$')
      continue
    }
    texts.push(lines[i])
  }
  return texts.join('\n')
}

export function escapeHTML(html: string) {
  return html.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}

//agent
const modelIconMap: Record<string, { iconName: string; menuIconName: string }> = {
  intelligent_authoring: {
    iconName: 'model-gongwen.svg',
    menuIconName: 'menu-model-gongwen.svg'
  },
  purchase_order_generate: {
    iconName: 'model-caigou.svg',
    menuIconName: 'menu-model-caigou.svg'
  },
  feasibility_report_review: {
    iconName: 'model-keyan.svg',
    menuIconName: 'menu-model-keyan.svg'
  },
  data_analysis: {
    iconName: 'model-wenshu.svg',
    menuIconName: 'menu-model-wenshu.svg'
  },
  knowledge_qa: {
    iconName: 'model-wps.svg',
    menuIconName: 'menu-model-wps.svg'
  },
  power_industry_news: {
    iconName: 'model-xinxikan.svg',
    menuIconName: 'menu-model-xinxikan.svg'
  },
  manuscript_proofreading: {
    //稿件校对员
    iconName: 'model-caigou.svg',
    menuIconName: 'menu-model-caigou.svg'
  },
  excel_formula: {
    //公式编辑器
    iconName: 'model-xinxikan.svg',
    menuIconName: 'menu-model-excel.svg'
  },
  ppt_outline: {
    //PPT大纲助手
    iconName: 'model-xinxikan.svg',
    menuIconName: 'menu-model-ppt.svg'
  },
  work_summary: {
    //工作总结大师
    iconName: 'model-caigou.svg',
    menuIconName: 'menu-model-caigou.svg'
  },
  it_tech: {
    //IT技术专家
    iconName: 'model-xinxikan.svg',
    menuIconName: 'menu-model-it.svg'
  }
}

function getAIAgentIconsWithType(type: string): any {
  // const iconObj = modelIconMap[type]

  // if (iconObj) {
  //   return iconObj
  // }
  return {
    iconName: 'model-default-icon.svg',
    menuIconName: 'model-default-icon.svg'
  }
}

export function createAndEnsureAIAgent(originalObject: any): AIAgent {
  // 检查原始对象是否已经满足部分条件
  const hasId = Object.prototype.hasOwnProperty.call(originalObject, 'id')
  const hasKey = Object.prototype.hasOwnProperty.call(originalObject, 'key')
  const hasName = Object.prototype.hasOwnProperty.call(originalObject, 'name')
  const { iconName, menuIconName } = getAIAgentIconsWithType(originalObject.key)
  // 创建一个新的对象，并复制原始对象的属性
  const agent: AIAgent = {
    ...originalObject,
    id: hasId ? originalObject.id : '',
    key: hasKey ? originalObject.key : '',
    name: hasName ? originalObject.name : '',
    icon: iconName,
    menuIcon: menuIconName,
    subTitle: originalObject.description,
    iconUrl: originalObject.icon_url,
    logoUrl: originalObject.logo_url,
    tag: originalObject.tag_name
  }

  return agent as AIAgent
}

// online messgae
const imagePathPrefix = 'apis'
export function onlineImagePathWithFileId(fileId: string): string {
  // 获取 authStore 实例
  const { getToken } = useAuthStore()
  const token = getToken() // 从 authStore 中获取 token

  const scheme = window.location.protocol
  const host = window.location.host

  const routerBasePath = localStorage.getItem('routerBasePath')
  // 构建基础 URL
  let url = `${scheme}//${host}${routerBasePath}${imagePathPrefix}/api/common/load_file`

  // 解析原始的查询参数
  const searchParams = new URLSearchParams(new URL(url).search)

  // 添加 token 参数
  searchParams.set('authorization', token)
  searchParams.set('file_name', fileId)

  // 将查询参数附加到 URL
  if (searchParams.toString()) {
    url += (url.includes('?') ? '&' : '?') + searchParams.toString()
  }

  return url
}

export function gotoChatPage(router: Router, agentId?: string, conversionId?: string) {
  const query: Record<string, any> = {}
  if (agentId) {
    query.agent_id = agentId
  }
  if (conversionId) {
    query.conversion_id = conversionId
  } else {
    query.new_chat = new Date().getTime()
  }
  router.push({
    name: 'homeView',
    query: query
  })
}
